package com.example.selfcontrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.selfcontrol.config.Response;
import com.example.selfcontrol.dto.ArticleInfoDTO;
import com.example.selfcontrol.dto.ArticleRespDTO;
import com.example.selfcontrol.dto.TalkRespDTO;
import com.example.selfcontrol.dto.WxArticleInfoDTO;
import com.example.selfcontrol.entity.*;
import com.example.selfcontrol.mapper.*;
import com.example.selfcontrol.service.ArticleService;
import com.example.selfcontrol.service.LikeOptService;
import com.example.selfcontrol.service.Mongo.ArticleInfoService;
import com.example.selfcontrol.service.StarOptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private StarOptMapper starOptMapper;
    @Autowired
    private LikeOptMapper likeOptMapper;
    @Autowired
    private ArticleInfoService articleInfoService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ArticleCategoryMapper articleCategoryMapper;


    @Autowired
    private StarOptService starOptService ;

    @Autowired
    private LikeOptService likeOptService ;


    @Override
    public Response getArticle(int articleId, int userId) {
        // userId == -1 表示游客访问，前端没有登录

        Article article = articleMapper.selectById(articleId);
        if (article == null) return Response.fail();

        int LikeNumber = likeOptService.CountLike((long)articleId) ;
        boolean isStar = starOptService.isUserStar(userId,(long)articleId) ;
        boolean isLike = likeOptService.isLike(userId,(long)articleId) ;


        // 装配DTO
        ArticleRespDTO articleRespDTO = new ArticleRespDTO(article, isStar, isLike, LikeNumber);

        return new Response(true, "200", articleRespDTO);
    }

    @Override
    public int ArticleCategoryCount(int cid) {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        if(cid != -1)  wrapper.eq("article_category", cid);
        return articleMapper.selectCount(wrapper);
    }

    // 创建文章
    @Override
    public Response createArticle(Article article) {
        try {
            articleMapper.insert(article);
            QueryWrapper<Article> queryWrapper = new QueryWrapper<>(article);
            Article article_back = articleMapper.selectOne(queryWrapper);
            System.out.println(article_back.getId());

            // 同步给MongoDB
//            articleInfoService.insertArticleInfo(article_back.getId(), article_back.getAuthorId(),
//                    article_back.getContent(), article_back.getArticleCategory(), article_back.getCreatetime());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail();
        }

        return Response.ok();
    }

    @Override
    public Response modifyArticle(Article article) {
        try {
            articleMapper.updateById(article);

        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail();
        }
        return Response.ok();
    }

    @Override
    public Response deleteArticle(Integer id) {
        try {
            articleMapper.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail();
        }
        return Response.ok();
    }

    @Override
    public List<Article> ArticleCategoryPagination(int cid, int pageNum, int pageSize) {
        Page<Article> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("article_category", cid);
        IPage<Article> iPage = articleMapper.selectPage(page, wrapper);

        //当前页的结果集
        return iPage.getRecords();
    }

    @Override
    public List<List<Article>> ArticleCategoryInfo() {
        List<List<Article>> SumList = new ArrayList<>();
        for (int cid = 1; cid <= 6; cid++) {
            List<Article> tmp = ArticleCategoryPagination(cid, 1, 5);
            SumList.add(tmp);
        }
        System.out.println("--------------  分类页面访问  -------------- ");
        return SumList;
    }

    @Override
    public List<ArticleInfoDTO> PersonalArticlesInfo(int userId, int pageNum, int pageSize) {
        Page<Article> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("author_id", userId);
        List<Article> articles = articleMapper.selectPage(page, wrapper).getRecords();

        List<ArticleInfoDTO> res = new ArrayList<>();
        for (Article x : articles) {
            String content = "" ;
            if(x.getContent() != null)
                content = x.getContent().substring(0, Math.min(x.getContent().length(),30)) ;   // 防止截取越界

            ArticleInfoDTO articleInfoDTO = new ArticleInfoDTO(content, x.getTitle(), x.getCreatetime(), x.getId());
            res.add(articleInfoDTO);
        }

        return res;
    }

    @Override
    public int CountPersonalArticles(Long userId) {
        QueryWrapper wrapper = new QueryWrapper<>() ;
        wrapper.eq("author_id",userId) ;
        return articleMapper.selectCount(wrapper) ;
    }

    @Override
    public List<Article> AllarticlesPagination(int pageNum, int pageSize) {
        Page<Article> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        IPage<Article> iPage = articleMapper.selectPage(page, wrapper);
        return iPage.getRecords();
    }


    @Override
    public List<ArticleCategory> getCategory() {
        QueryWrapper<ArticleCategory> queryWrapper = new QueryWrapper<>() ;
        queryWrapper.eq("type",0) ;

        List<ArticleCategory> res = articleCategoryMapper.selectList(queryWrapper);
        return res;
    }

    @Override
    public List<ArticleCategory> getTalkType() {
        QueryWrapper<ArticleCategory> queryWrapper = new QueryWrapper<>() ;
        queryWrapper.eq("type",1) ;

        List<ArticleCategory> res = articleCategoryMapper.selectList(queryWrapper);
        return res;
    }

    @Override
    public List<WxArticleInfoDTO> getWxArticleInfo(int cid, int userId, int pageNum, int pageSize, int sortBy) {
        // 处理越界异常
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>() ;
        if(cid != -1)  wrapper.eq("article_category", cid);

        int articleCount = articleMapper.selectCount(wrapper) ;
        if(articleCount <= pageNum * pageSize)
            return new ArrayList<>() ;

        if(sortBy == 1) {
            // 找到最新的文章 --- 页数反转
            int PageCount = articleCount / pageSize ;
            int findPage = PageCount - 1 - pageNum ;
            pageNum = findPage ;
        }
        else if(sortBy == 2)   queryWrapper.orderBy(true,false,"up") ;       // 按照点赞降序

        // 增加排序
        wrapper.clear();
        Page<Article> page = new Page<>(pageNum, pageSize);

        List<Article> articles = articleMapper.selectPage(page, queryWrapper).getRecords();

        List<Article> filter = new ArrayList<>() ;
        if(cid != -1) {
            List<Article> filterArticles = articles.stream()
                    .filter(article -> article.getArticleCategory() == cid)
                    .collect(Collectors.toList());
            filter = filterArticles ;
        }

        if(cid == -1)   filter = articles ;

        List<WxArticleInfoDTO> result = new ArrayList<>();
        for (Article article : filter) {
            Long authorId = article.getAuthorId();
            User user = userMapper.selectById(authorId);
            String authorName = user.getNickName();

            String ImgURL = user.getPicture();

            int starCount = starOptService.CountStar(article.getId()) ;
            int likeCount = likeOptService.CountLike(article.getId()) ;

            // 处理 截取异常
            String Sbrief = "" ;
            if(article.getContent().length() > 80)
                Sbrief = article.getContent().substring(0, 80) ;

            WxArticleInfoDTO tmp = new WxArticleInfoDTO(article.getId(),
                    ImgURL, authorName, article.getTitle(),Sbrief
                    ,article.getCreatetime(),article.getArticleCategory(),starCount,likeCount);


            boolean isStar = starOptService.isUserStar(userId,article.getId()) ;
            boolean isLike = likeOptService.isLike(userId,article.getId()) ;

            tmp.setIsLike(isLike);
            tmp.setIsStar(isStar);
            result.add(tmp);
        }

        return result ;
    }

    @Override
    public List<Article> SearchWordContained(String word, int pageNum, int pageSize) {
        Page<Article> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Article> wrapper = new QueryWrapper<>() ;
        wrapper.like("content",word) ;

        return articleMapper.selectPage(page,wrapper).getRecords() ;
    }

    // 更新文章状态
    @Override
    public Response UpdateArticle(Long articleId,Long untilId) {
        System.out.println(articleId);
        System.out.println(untilId);

        for(Long i = articleId ; i <= untilId ; i++) {
            int starNumber = starOptService.CountStar(articleId) ;
            int likeNumber = likeOptService.CountLike(articleId) ;

            Article article = articleMapper.selectById(articleId) ;
            article.setUp(likeNumber);
            article.setStars(starNumber);
            articleMapper.updateById(article) ;
        }

        return Response.ok() ;
    }

    // 获取 说说 的Info
    @Override
    public List<TalkRespDTO> getTalkInfoList(int userId, int pageNum, int pageSize) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>() ;
        queryWrapper.eq("type",1) ;
        queryWrapper.orderByDesc("createtime") ;
        Page<Article> page = new Page<>(pageNum, pageSize);
        List<Article> talks = articleMapper.selectPage(page, queryWrapper).getRecords();

        List<TalkRespDTO> res = new ArrayList<>() ;

        for(Article items : talks) {
            Long authorId = items.getAuthorId() ;

            // 作者信息
            User user = userMapper.selectById(authorId) ;
            String AuthorImg = user.getPicture() ;
            String AuthorName = user.getNickName() ;

            // 点赞信息 | 是否点赞
            boolean isLike = likeOptService.isLike(userId,items.getId()) ;
            int LikeNumber = likeOptService.CountLike(items.getId()) ;

            // 处理图片Url
            List<String> ImgList = new ArrayList<>() ;
            if(items.getImgList() != null) {
                String[] urlArray = items.getImgList().split(";") ;

                for(String url : urlArray)
                    ImgList.add(url) ;
            }

            // 处理brief
            String content = items.getContent() ;
            String TalkBrief , FullTalk ;
            if(content.length() > 60) {
                TalkBrief = content.substring(0,60) ;
                FullTalk = content ;
            }else {
                TalkBrief = FullTalk = content ;
            }

            // 装载DTO
            TalkRespDTO tmp = new TalkRespDTO(items.getId(),AuthorImg,AuthorName,TalkBrief,FullTalk,items.getCreatetime(),
                    items.getArticleCategory(),LikeNumber,ImgList,isLike) ;

            res.add(tmp) ;
        }

        return res ;
    }
}